#-*- coding: utf-8 -*
#from twisted.web.html import output

from config import global_lookup
from web.utils import storage
from config import TP_PATH
import os,web
import time
import datetime
import json

def checkFields(obj,keys):
    """
    检查对象属性是否齐备
    @param obj:对象名
    @param keys: 属性名列表
    @return:True or False
    """
    try:
        nkeys=obj.keys()
        for k in keys:
            if k not in nkeys:
                return False
        return True
    except:
        return False


def format_money_two(money):
    """
    增加千分位显示
    @param money:
    @return:
    """
    if money is None:money=0
    if money =='' :money=0
    pattern = '{:,}'.format(money)
    return pattern
def RemoveMoneyTag(money):
    """
    去除金额的千分位符号
    @param money:
    @return:
    """
    money=str(money).replace(',','')
    return money

def CalMonthLastDate(year,month):
    """
    计算某月的最后一天日期
    @param year:
    @param month:
    @return:
    """
    d2=datetime.date(year,month+1,1)-datetime.timedelta(days=1)
    return d2
def CalMonthDays(year,month):
    """
    计算某月的天数
    @param year:
    @param month:
    @return:
    """
    days=0
    if month==12:
        days=31
    else:
        d1=datetime.date(year,month,1)
        d2=CalMonthLastDate(year,month)
        days=(d2-d1).days+1
    return days
def BlankToValue(obj,fields,value):
    for f in fields:
        if obj.has_key(f):
            if obj[f]=='':
                obj[f]=value
    return  obj
def BlankToNone(obj,fields):
    return BlankToValue(obj,fields,None)
def Show404():
    t=global_lookup.get_template("T/404.html")
    strs= t.render()
    web.ctx.status = '404 Not Found'
    web.header('Content-Type', 'text/html')
    return strs
def TimeStr(fmt="%Y%m%d%H%M%S"):
    return time.strftime(fmt)
def JsonResult(value):
    """
    返回json编码后的result数据值
    @param value:需要放入result的数据
    @return:{"result":value}json处理后
    """
    return json.dumps({"result":value})
def GetPreMonth(year,month):
    if month==1:
        year=year-1
        month=12
    else:
        month=month-1
    return year,month
def ArrayFind(array,value):
    """
    在数组中查找值
    """
    i=0
    fl=False
    for a in array:
        i+=1
        if a==value:
            fl=True
            break

    if fl:
        return i
    else:
        return -1
def InitStorage(storage,incfields=[],defaultvalue=""):
    """
    用于初始化storage，补充属性值
    @param storage:需要初始化的storage
    @param incfields:涉及的字段
    @param defaultvalue:默认值
    @return:storage,初始化好的对象
    """
    if incfields:
        for field in incfields:
            if storage.get(field,defaultvalue)==defaultvalue or storage[field]==None:   #不污染原有值
                storage[field]=defaultvalue
    else:
        for field in storage.keys:
            if storage.get(field,defaultvalue)==defaultvalue or storage[field]==None:   #不污染原有值
                storage[field]=defaultvalue
    #初始化好的对象
    return storage
def InitStorageBlank(storage,incfields=[]):
    """
    用于初始化storage或dic,将incfields包含的字段赋值，如果有值则传，无值则初始化为""
    给定字段则按给定字段
    """
    if incfields:
        for field in incfields:
            if storage.get(field,None)==None:   #不污染原有值
                storage[field]=""
    else:
        for field in storage.keys():
            if storage.get(field,None)==None:   #不污染原有值
                storage[field]=""
    return storage
def CopyData_INC(storage1,storage2,incfields=[],default=None):
    """合并属性，将storage2由incfields指定的字段合并入storage1中。
    如属性在2中为None，则不指定
    """
    for field in incfields:
        if storage2.get(field,None) is None:
            storage1[field]=default
        else:
            storage1[field]=storage2[field]
    return storage1
def CopyData_EX(storage1,storage2,exfields=["id"]):
    """
    合并属性,如果storage1、2共有的属性按2更新1的属性值，如2有1无的，不作处理
    1有2无的也不作处理
    exfiles=["id","no"]不想受此次复制污染的字段
    """
    a=[]
    if not storage1:                    #如果给的是一个None空，则先初始化一下。
        storage1=storage()
    for k in storage2.keys():
        if ArrayFind(exfields,k)==-1:
            storage1[k]=storage2[k]
    return storage1
def CopyData(storage1,storage2):
    """
    合并属性,如果storage1、2共有的属性按2更新1的属性值，如2有1无的，不作处理
    1有2无的也不作处理
    """
    if not storage1:                    #如果给的是一个None空，则先初始化一下。
        storage1=storage()
    for k in storage2.keys():
        storage1[k]=storage2[k]
    return storage1
def CopyData_Match(storage1,storage2,fields1=[],fields2=[]):
    """
    按配置字段将storage2的数据赋值给storage1
    @param fields1:storage1需要赋值的字段
    @param fields2:storage2提供数据的字段
    @param storage1:需要被赋值的storage
    @param storage2:提供数据的storage
    @reaturn:storage1
    """
    if len(fields1)==len(fields2) and len(fields1)>0:
        for i in range(len(fields1)):
            storage1[fields1[i]]=storage2[fields2[i]]
        return storage1
    else:
        raise Exception,u"字段数量不对应或未配置"
def AShowOkMsg(msg,href,urltype):
    lookup=global_lookup
    t=lookup.get_template("T/msgbox.html")
    return t.render(msg=msg,href=href,type="OK",urltype=urltype)
def AShowErrorMsg(msg,href,urltype):
    lookup=global_lookup
    t=lookup.get_template("T/msgbox.html")
    return t.render(msg=msg,href=href,type="Error",urltype=urltype)

def ShowErrorAndGoBack(msg):
    return AShowErrorMsg(msg,"history.go(-1)",1)

def ShowOkAndGoBack(msg):
    return AShowOkMsg(msg,"history.go(-1)",1)

def ShowOkMsg(msg,href):
    return AShowOkMsg(msg,href,0)

def ShowErrorMsg(msg,href):
    return AShowErrorMsg(msg,href,0)

def getMD5(src):
    """
    用于生成md5串
    """
    import hashlib
    return hashlib.md5(src).hexdigest()
def safewhere(s):
    """
    用于过滤注入句语
    ...
    sql = "parent_id in (SELECT id FROM t_Menu WHERE module_code = '"+qn(md_code)+"')"
    ....
    """
    dirty_stuff = ["\"", "\\", "/", "*", "'", "=", "-", "#", ";", "<", ">", "+", "%"]
    for stuff in dirty_stuff:
        s = s.replace(stuff,"")
    return s
def toJson(obj):
    """
    将对象转换成json串,
    一般入口请使用web.utils的storage对象
    """
    import json
    try:
        return json.dumps(obj)
    except :
        return ""

def uploadFile(obj,path,filename):
    try:
            strBaseLocation=TP_PATH+path
            nfilename=strBaseLocation+filename
            #excel需要使用二进制写入打开参数需要wb
            fout=open(nfilename,'wb')
            fout.write(obj.file.read())
            fout.close()
            return True
    except :
            return False

def uploadAttachment(obj):
        fileextname = os.path.splitext(obj.filename)[1]
        filefullname = time.strftime("%Y%m%d%H%M%S")+fileextname
        if uploadFile(obj,"/static/attachment/",filefullname):
            return filefullname
        else:
            return None

def StringToInt(str,default=-1):
    try:
        return int(str)
    except:
        return default

def StringToFloat(str,default=-1.0):
    try:
        return float(str)
    except:
        return default


def ExcelDateToDate(edate):
    if isinstance(edate,(int,float)):
        dstr=datetime.datetime.strptime("1900-1-1","%Y-%m-%d")+ datetime.timedelta(edate-2)
        return dstr.date()
    else:
        return edate


if __name__=="__main__":
    print getMD5("abcdefge")
    print toJson({'a':12,"b":"aaaa"})

    print ExcelDateToDate(22222)